<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库编码" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择">
          <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseCode" :value="item.id">
            <span style="float: left">{{ item.warehouseCode }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.warehouseName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入用户名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="4">
        <!-- 视图切换按钮 -->
        <el-radio-group v-model="viewMode" @change="handleViewModeChange" size="mini">
          <el-radio-button label="user">用户视图</el-radio-button>
          <el-radio-button label="warehouse">仓库视图</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:permission:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:permission:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:permission:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:permission:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 树形表格 -->
    <el-table v-loading="loading" :data="treeData" @selection-change="handleSelectionChange"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" row-key="id">
      <el-table-column type="selection" width="55" align="center" />

      <!-- 根据视图模式显示不同的列 -->
      <el-table-column label="名称" align="center" width="200">
        <template slot-scope="scope">
          <template v-if="viewMode === 'user'">
            {{ scope.row.type === 'user' ? scope.row.userName : scope.row.warehouseCode }}
          </template>
          <template v-else>
            {{ scope.row.type === 'warehouse' ? scope.row.warehouseCode : scope.row.userName }}
          </template>
        </template>
      </el-table-column>

      <el-table-column label="类型" align="center" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type === 'user'" type="success">用户</el-tag>
          <el-tag v-if="scope.row.type === 'warehouse'" type="primary">仓库</el-tag>
          <el-tag v-if="scope.row.type === 'permission'" type="info">权限</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <template v-if="scope.row.type === 'permission'">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:permission:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:permission:remove']">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改仓库权限对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库编码" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseCode" :value="item.id">
              <span style="float: left">{{ item.warehouseCode }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.warehouseName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择">
            <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
              <span style="float: left">{{ item.userName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.nickName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPermission, getPermission, delPermission, addPermission, updatePermission } from "@/api/system/permission"
import { listWarehouse } from "@/api/system/warehouse"
import { listUser } from "@/api/system/user"

export default {
  name: "Permission",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 原始权限列表数据
      permissionList: [],
      // 树形结构数据
      treeData: [],
      // 用户列表
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 视图模式：user-用户视图，warehouse-仓库视图
      viewMode: "user",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        userId: null,
      },
      // 仓库选择
      warehouseList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseId: [
          { required: true, message: "仓库ID不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.warehouseQuery()
    this.userQuery() // 加载用户列表
  },
  methods: {
    /** 查询仓库权限列表 */
    getList() {
      this.loading = true
      listPermission(this.queryParams).then(response => {
        this.permissionList = response.rows
        this.total = response.total
        // 根据当前视图模式构建树形数据
        this.buildTreeData()
        this.loading = false
      })
    },
    /** 仓库查询 */
    warehouseQuery() {
      listWarehouse().then(response => {
        this.warehouseList = response.rows
      })
    },
    /** 用户查询 */
    userQuery() {
      listUser().then(response => {
        this.userList = response.rows
      })
    },
    /** 构建树形数据 */
    buildTreeData() {
      if (this.viewMode === 'user') {
        this.buildUserTree()
      } else {
        this.buildWarehouseTree()
      }
    },
    /** 构建用户视图树形结构：用户 -> 仓库 */
    buildUserTree() {
      // 1. 建立用户映射表
      const userMap = {}
      this.userList.forEach(user => {
        userMap[user.id] = {
          id: `user_${user.id}`,
          type: 'user',
          userName: user.userName,
          createBy: user.createBy,
          createTime: user.createTime,
          children: []
        }
      })

      // 2. 将权限分配到对应的用户下
      this.permissionList.forEach(permission => {
        if (!userMap[permission.userId]) return

        // 查找对应的仓库信息
        const warehouse = this.warehouseList.find(w => w.id === permission.warehouseId)

        // 添加仓库作为用户的子节点
        userMap[permission.userId].children.push({
          ...permission,
          type: 'permission',
          warehouseCode: warehouse ? warehouse.warehouseCode : '未知仓库',
          warehouseName: warehouse ? warehouse.warehouseName : ''
        })
      })

      // 3. 转换为数组并过滤没有权限的用户
      this.treeData = Object.values(userMap).filter(user => user.children.length > 0)
    },
    /** 构建仓库视图树形结构：仓库 -> 用户 */
    buildWarehouseTree() {
      // 1. 建立仓库映射表
      const warehouseMap = {}
      this.warehouseList.forEach(warehouse => {
        warehouseMap[warehouse.id] = {
          id: `warehouse_${warehouse.id}`,
          type: 'warehouse',
          warehouseCode: warehouse.warehouseCode,
          warehouseName: warehouse.warehouseName,
          createBy: warehouse.createBy,
          createTime: warehouse.createTime,
          children: []
        }
      })

      // 2. 将权限分配到对应的仓库下
      this.permissionList.forEach(permission => {
        if (!warehouseMap[permission.warehouseId]) return

        // 查找对应的用户信息
        const user = this.userList.find(u => u.id === permission.userId)

        // 添加用户作为仓库的子节点
        warehouseMap[permission.warehouseId].children.push({
          ...permission,
          type: 'permission',
          userName: user ? user.userName : '未知用户'
        })
      })

      // 3. 转换为数组并过滤没有权限的仓库
      this.treeData = Object.values(warehouseMap).filter(warehouse => warehouse.children.length > 0)
    },
    /** 视图模式切换 */
    handleViewModeChange() {
      this.buildTreeData()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        warehouseId: null,
        userId: null,
        creatorId: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // 只处理权限类型的节点
      const permissionNodes = selection.filter(item => item.type === 'permission')
      this.ids = permissionNodes.map(item => item.id)
      this.single = permissionNodes.length !== 1
      this.multiple = !permissionNodes.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加仓库权限"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPermission(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改仓库权限"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePermission(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            // 添加创建人信息
            this.form.creatorId = this.$store.getters.userId;
            addPermission(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除选中的权限数据？').then(function () {
        return delPermission(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/permission/export', {
        ...this.queryParams
      }, `permission_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
